package com.xh.bussiness.tiku.service.impl;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.xh.bussiness.tiku.bean.dto.ImportQuestionResultDto;
import com.xh.bussiness.tiku.bean.dto.QuestionDto;
import com.xh.bussiness.tiku.bean.request.QuestionImportLogRequest;
import com.xh.bussiness.tiku.constant.TikuEsContant;
import com.xh.bussiness.tiku.dao.PaperQuestionMapper;
import com.xh.bussiness.tiku.dao.QuestionImportLogMapper;
import com.xh.bussiness.tiku.model.QuestionFailInfo;
import com.xh.bussiness.tiku.model.QuestionImportLog;
import com.xh.bussiness.tiku.model.QuestionTypeRelation;
import com.xh.bussiness.tiku.service.IQuestionImportLogService;
import com.xh.bussiness.tiku.service.IQuestionService;
import com.xh.bussiness.tiku.service.IQuestionTypeRelationService;
import com.xh.bussiness.tiku.util.QuestionUtils;
import com.xh.core.bean.XhPage;
import com.xh.core.exception.XhException;
import com.xh.core.service.IElasticSearchService;
import com.xh.core.service.impl.BaseServiceImpl;
import com.xh.core.util.HtmlUtils;
import com.xh.core.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.stream.Collectors;

/**
 * <p>
 * 试题导入记录表 服务实现类
 * </p>
 *
 * @author daiwei
 * @since 2019-07-05
 */
@Service
public class QuestionImportLogServiceImpl extends BaseServiceImpl<QuestionImportLogMapper, QuestionImportLog> implements IQuestionImportLogService {

    @Autowired
    private IQuestionService questionService;
    @Autowired
    private IQuestionTypeRelationService questionTypeRelationService;
    @Autowired
    private IElasticSearchService elasticSearchService;
    @Autowired
    private PaperQuestionMapper paperQuestionMapper;

    @Override
    public XhPage queryQuestionImportLogPage(XhPage page, QuestionImportLogRequest bean) {
        QueryWrapper qw = new QueryWrapper<QuestionImportLog>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return (XhPage) this.dao.selectPage(page, qw);
    }

    @Override
    public List queryQuestionImportLog(QuestionImportLogRequest bean) {
        QueryWrapper qw = new QueryWrapper<QuestionImportLog>();
        //拼装条件
        qw = prepareParams(bean, qw);

        return this.dao.selectList(qw);
    }

    @Override
    public Map<String, Object> queryQuestionByImportId(String importId) {
        QuestionImportLog questionImportLog = this.getById(importId);
        if (questionImportLog == null) {
            throw new XhException("导入试题日志不存在");
        }
        if (StringUtils.isEmpty(questionImportLog.getQuestionIds())) {
            throw new XhException("导入试题不存在");
        }
        String[] questionIds = questionImportLog.getQuestionIds().split(",");
        List<QuestionDto> resultList = new ArrayList<>();
        List<QuestionFailInfo> failInfos = new ArrayList<>();
        int index = 0;
        long startTime = System.currentTimeMillis();
        for (String questionId : questionIds) {
            index++;
            long startTime1 = System.currentTimeMillis();
            QuestionDto question = questionService.getQuestion(questionId, null, true, true, true, true, true);
            long endTime = System.currentTimeMillis();
            System.out.println("单题查询时间：" + (endTime - startTime1));
            if (question == null) {
                continue;
            }
            long startTime2 = System.currentTimeMillis();
//            question = questionService.formatQuestion(question);
//            if (question.getType() == 0) {
//                question.setBasicQuestionType(question.getBasicQuestionType());
//                question.setQuestionTypeName(question.getBasicQuestionTypeName());
//            } else {
//                String questionTypeStr = getQuestionTypeStr(questionImportLog.getSubjectId(), question.getType());
//                if (!StringUtils.isEmpty(questionTypeStr)) {
//                    question.setQuestionTypeName(questionTypeStr);
//                } else {
//                    question.setType(null);
//                }
//            }
            //查询是否重复率到80%
            getRepetitionRate(question);
            endTime = System.currentTimeMillis();
            System.out.println("单题计算相似度时间：" + (endTime - startTime2));
            question.setOptionNum(QuestionUtils.calculateOptionArrange(question.getOptions()));
            resultList.add(question);

            //获取有错误信息的数据
            if (StringUtils.isNotEmpty(question.getFailReason())) {
                QuestionFailInfo questionFailInfo = new QuestionFailInfo();
                questionFailInfo.setQuesId(question.getId());
                questionFailInfo.setQuesType(question.getType());
                questionFailInfo.setErrMsg(question.getDataErrorMsg());
                questionFailInfo.setIndex(index + "");
                failInfos.add(questionFailInfo);
            }
        }
        long endTime = System.currentTimeMillis();
        System.out.println("总运行时间：" + (endTime - startTime));
        //按照题目类型排序
//        resultList = resultList.stream().sorted(Comparator.comparing(QuestionDto::getType)).collect(Collectors.toList());
        //根据试题类型分组
//        Map<Integer, List<QuestionDto>> resultMap = resultList.stream().collect(Collectors.groupingBy(item -> item.getType()));
//        //拼装返回值
//        List<ImportQuestionResultDto> ret = new ArrayList<>();
//        if (!CollectionUtils.isEmpty(resultMap)) {
//            resultMap.forEach((k,v)->{
//                ImportQuestionResultDto importQuestionResultDto = new ImportQuestionResultDto();
//                importQuestionResultDto.setQuestionType(k);
//                boolean empty = CollectionUtils.isEmpty(v);
//                importQuestionResultDto.setQuestionTypeName(empty?"":v.get(0).getQuestionTypeName());
//                importQuestionResultDto.setQuestionDtos(empty ? new ArrayList<>() : v);
//
//                ret.add(importQuestionResultDto);
//            });
//        }
        Map result = new HashMap();
        result.put("failInfo", failInfos);
        result.put("questionList", resultList);
        result.put("paperId", questionImportLog.getPaperId());
        return result;
    }

    @Override
    public QuestionDto quoteQuestionToImportLog(String importId, String quoteQuestionId, String importQuestionId) {
        QuestionImportLog log = this.getById(importId);
        if (log == null) {
            throw new XhException("导入记录不存在");
        }
        QuestionDto quoteQuestion = questionService.getQuestion(quoteQuestionId, null);
        if (quoteQuestion == null) {
            throw new XhException("引用试题不存在");
        }
        //删除导入试题，添加引用试题
        questionService.deleteQuestion(importQuestionId);

        String newQuestionIds = log.getQuestionIds().replaceAll(importQuestionId, quoteQuestionId);
        log.setQuestionIds(newQuestionIds);
        this.update(log);

        return quoteQuestion;
    }

    @Override
    public void removeLogPaperByPaperId(String paperId) {
        QueryWrapper qw = new QueryWrapper();
        qw.eq("paper_id", paperId);
        List<QuestionImportLog> list = this.dao.selectList(qw);
        for (QuestionImportLog log : list) {
            log.setPaperId(null);
            this.update(log);
        }
    }

    private void getRepetitionRate(QuestionDto question) {
//        String content = HtmlUtils.delHTMLTag(question.getTitle() + question.getOptionStr());
//        Map matchQueryPercent = elasticSearchService.matchQueryPercent("subjectId", question.getSubjectId(), "title", content, "95%", TikuEsContant.ES_INDEX_TIKU,
//                TikuEsContant.TYPE.ES_INDEX_TYPE_QUESTION);
//        Object hits = matchQueryPercent.get("hits");
//        if (null == hits) {
//            return;
//        }
//        Object result = ((Map) hits).get("hits");
//        List<Map> detials = (List<Map>) result;
//        List<Map<String, String>> repeatInfos = new ArrayList<>(detials.size());
//        // 获取最大相似度
//        Double similarDegree = 0.0;
//        for (Map detial : detials) {
//            String esQuestionId = detial.get("_id").toString();
//            if (esQuestionId.equals(question.getId())) {
//                continue;
//            }
//            String compareContent = (String) ((Map) (detial.get("_source"))).get("title");
//            Double degree = StringUtils.SimilarDegree(content, compareContent);
//            if (similarDegree < degree) {
//                similarDegree = degree;
//            }
//            Map<String, String> repeatInfo = new HashMap<>(2);
//            repeatInfo.put("questionId", detial.get("_id").toString());
//            repeatInfo.put("similarDegree", degree.toString());
//            repeatInfos.add(repeatInfo);
//        }
//        if (detials.size() > 0 && !similarDegree.equals(0.0)) {
//            question.setSimilarDegree(similarDegree.toString());
//            question.setRepeatInfos(repeatInfos);
//        }
    }


    private String getQuestionTypeStr(String subject, Integer jyQuestionType) {
        QuestionTypeRelation questionTypeRelation =
                questionTypeRelationService.queryByJyQuestionType(subject, jyQuestionType);
        if (questionTypeRelation != null) {
            return questionTypeRelation.getJyQuestionTypeName();
        }
        return "未识别题型";
//        return "";
    }


    /**
     * 准备条件
     *
     * @param bean
     * @param qw
     */
    private QueryWrapper prepareParams(QuestionImportLogRequest bean, QueryWrapper qw) {
        if (bean.getIds() != null && bean.getIds().length > 0) {
            qw.in("id", bean.getIds());
        }
        if (!StringUtils.isEmpty(bean.getUserId())) {
            qw.eq("creator_id", bean.getUserId());
        }
        if (bean.getSchoolId() != null) {
            qw.eq("school_id", bean.getSchoolId());
        }
        if (bean.getSubjectId() != null) {
            qw.eq("subject_id", bean.getSubjectId());
        }
        if(StringUtils.isNotEmpty(bean.getFileName())){
            qw.like("file_name", bean.getFileName());
        }
        qw.orderByDesc("create_time");
        return qw;
    }

    /**
     * 根据试卷id获取试题（批量录题学科网）
     * @author 赵文博
     * @date 2021/6/2 15:14
     * @param paperId
     * @return java.util.Map<java.lang.String,java.lang.Object>
     **/
    @Override
    public Map<String, Object> queryQuestionByPaperId(String paperId) {
        List<String> questionIds = paperQuestionMapper.queryQuestionIdByPaperId(paperId);
        List<QuestionDto> resultList = new ArrayList<>();
        List<QuestionFailInfo> failInfos = new ArrayList<>();
        int index = 0;
        for (String questionId : questionIds) {
            index++;
            long startTime1 = System.currentTimeMillis();
            QuestionDto question = questionService.getQuestion(questionId, null, true, true, true, true, true);
            long endTime = System.currentTimeMillis();
            System.out.println("单题查询时间：" + (endTime - startTime1));
            if (question == null) {
                continue;
            }
            //查询是否重复率到80%
            getRepetitionRate(question);
//            question.setOptionNum(QuestionUtils.calculateOptionArrange(question.getOptions()));
            resultList.add(question);

            //获取有错误信息的数据
            if (StringUtils.isNotEmpty(question.getFailReason())) {
                QuestionFailInfo questionFailInfo = new QuestionFailInfo();
                questionFailInfo.setQuesId(question.getId());
                questionFailInfo.setQuesType(question.getType());
                questionFailInfo.setErrMsg(question.getDataErrorMsg());
                questionFailInfo.setIndex(index + "");
                failInfos.add(questionFailInfo);
            }
        }
        Map result = new HashMap();
        result.put("failInfo", failInfos);
        result.put("questionList", resultList);
        result.put("paperId", paperId);
        return result;
    }
}
